package com.beemans.topon.kts

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken

/**
 * @author ti
 * @date 2022/11/23.
 */
inline fun <reified T> String?.fromJson(): T? = GsonKt.fromJson(this)

fun Any?.toJson(): String? = GsonKt.toJson(this)

/**
 * 深度克隆
 */
inline fun <reified T> T.deepClone(): T? {
    val str = toJson()
    return str.fromJson()
}

object GsonKt {
    val gson: Gson by lazy { GsonBuilder().create() }

    inline fun <reified T> fromJson(str: String?): T? {
        str ?: return null
        kotlin.runCatching {
            val type = object : TypeToken<T>() {}.type
            return gson.fromJson(str, type)
        }
        return null
    }

    fun toJson(any: Any?): String? {
        any ?: return null
        kotlin.runCatching {
            return gson.toJson(any)
        }
        return null
    }
}